package handler

import (
	"cangqiong-takeout/src/common"
	"cangqiong-takeout/src/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func HandlerFuncUser() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("token")
		id, name, pwd, err := utils.DecodeToken(token)
		if token == "" || err != nil || id == 0 || name == "" || pwd == "" {
			utils.ResponseBad(c, common.InsufficientPermissions, nil)
			c.Abort()
			return
		}
		if reslut := utils.MysqlDB.Table("employee").Where("username=? AND pwd=?", name, pwd); errors.Is(reslut.Error, gorm.ErrRecordNotFound) {
			utils.ResponseBad(c, common.InsufficientPermissions, nil)
			c.Abort()
			return
		}
		c.Set("userid", id) //当前登录用户id
		c.Next()
	}
}
